package com.liuwei.msmall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * @Classname MyCacheConfig
 * @Description TODO
 * @Date 2020/6/18 11:59
 * @Created by 刘
 */
//自定义缓存配置
@EnableConfigurationProperties(CacheProperties.class)//绑定配置文件
@EnableCaching
@Configuration
public class MyCacheConfig {


    //springboot默认在方法参数中的对象自动装配
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //重新配置redisManager的value值序列化规则为json格式
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //配置redis缓存中key的过期时间
        if (redisProperties.getTimeToLive() != null) {

            Duration timeToLive = redisProperties.getTimeToLive();
            long seconds = timeToLive.getSeconds();
            //重配置文件中取值，
            System.out.println("从配置文件中取出的key的过期时间："+seconds+"秒");
            config = config.entryTtl(redisProperties.getTimeToLive());
        }

        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }



}
